// 布局状态持久化 composable

import { ref, watch, onMounted, onUnmounted } from 'vue'
import { useUIStore } from '@/stores/ui'
import { STORAGE_KEYS } from '@/constants'

interface LayoutState {
  sidebarCollapsed: boolean
  sidebarVisible: boolean
  clientInfoVisible: boolean
  clientInfoExpanded: boolean
  activeTab: string
  theme: string
  density: string
  layoutMode: string
  panelStates: Record<string, boolean>
  windowSize: {
    width: number
    height: number
  }
  lastBreakpoint: string
}

export function useLayoutPersistence() {
  const uiStore = useUIStore()
  const isInitialized = ref(false)
  const saveTimeout = ref<NodeJS.Timeout>()

  // 防抖保存函数
  const debouncedSave = (state: LayoutState) => {
    if (saveTimeout.value) {
      clearTimeout(saveTimeout.value)
    }
    
    saveTimeout.value = setTimeout(() => {
      saveLayoutState(state)
    }, 300)
  }

  // 保存布局状态到 localStorage
  const saveLayoutState = (state: LayoutState) => {
    try {
      const stateToSave = {
        ...state,
        timestamp: Date.now(),
        version: '1.0'
      }
      
      localStorage.setItem(STORAGE_KEYS.LAYOUT_STATE, JSON.stringify(stateToSave))
      
      // 同时保存到 sessionStorage 作为备份
      sessionStorage.setItem(STORAGE_KEYS.LAYOUT_STATE, JSON.stringify(stateToSave))
      
    } catch (error) {
      console.warn('Failed to save layout state:', error)
    }
  }

  // 从存储中加载布局状态
  const loadLayoutState = (): LayoutState | null => {
    try {
      // 优先从 localStorage 加载
      let stored = localStorage.getItem(STORAGE_KEYS.LAYOUT_STATE)
      
      // 如果 localStorage 没有，尝试从 sessionStorage 加载
      if (!stored) {
        stored = sessionStorage.getItem(STORAGE_KEYS.LAYOUT_STATE)
      }
      
      if (stored) {
        const state = JSON.parse(stored)
        
        // 检查版本兼容性
        if (state.version && state.version !== '1.0') {
          console.warn('Layout state version mismatch, using defaults')
          return null
        }
        
        // 检查时间戳，如果超过30天则忽略
        if (state.timestamp && Date.now() - state.timestamp > 30 * 24 * 60 * 60 * 1000) {
          console.info('Layout state expired, using defaults')
          return null
        }
        
        return state
      }
    } catch (error) {
      console.warn('Failed to load layout state:', error)
    }
    
    return null
  }

  // 获取默认布局状态
  const getDefaultLayoutState = (): LayoutState => ({
    sidebarCollapsed: false,
    sidebarVisible: false,
    clientInfoVisible: true,
    clientInfoExpanded: false,
    activeTab: 'chats',
    theme: 'auto',
    density: 'normal',
    layoutMode: 'auto',
    panelStates: {
      sidebar: true,
      tabs: true,
      clientInfo: true,
      notifications: false,
      settings: false
    },
    windowSize: {
      width: window.innerWidth,
      height: window.innerHeight
    },
    lastBreakpoint: 'desktop'
  })

  // 应用布局状态到 store
  const applyLayoutState = (state: LayoutState) => {
    try {
      // 应用基本状态
      uiStore.setSidebarCollapsed(state.sidebarCollapsed)
      uiStore.setClientInfoVisible(state.clientInfoVisible)
      uiStore.setActiveTab(state.activeTab)
      
      // 应用主题和密度
      if (state.theme) {
        uiStore.setTheme(state.theme as any)
      }
      
      // 应用面板状态
      if (state.panelStates) {
        Object.entries(state.panelStates).forEach(([panel, visible]) => {
          uiStore.setPanelState(panel, visible)
        })
      }
      
      // 应用布局模式
      if (state.layoutMode) {
        uiStore.setLayoutMode(state.layoutMode as any)
      }
      
    } catch (error) {
      console.warn('Failed to apply layout state:', error)
    }
  }

  // 从 store 收集当前状态
  const collectCurrentState = (): LayoutState => ({
    sidebarCollapsed: uiStore.sidebarCollapsed,
    sidebarVisible: uiStore.sidebarVisible,
    clientInfoVisible: uiStore.clientInfoVisible,
    clientInfoExpanded: uiStore.clientInfoExpanded,
    activeTab: uiStore.activeTab,
    theme: uiStore.theme,
    density: uiStore.density,
    layoutMode: uiStore.layoutMode,
    panelStates: { ...uiStore.panelStates },
    windowSize: {
      width: uiStore.windowWidth,
      height: uiStore.windowHeight
    },
    lastBreakpoint: uiStore.currentBreakpoint
  })

  // 重置布局到默认状态
  const resetLayout = () => {
    const defaultState = getDefaultLayoutState()
    applyLayoutState(defaultState)
    saveLayoutState(defaultState)
  }

  // 导出布局配置
  const exportLayout = (): string => {
    const state = collectCurrentState()
    return JSON.stringify(state, null, 2)
  }

  // 导入布局配置
  const importLayout = (configJson: string): boolean => {
    try {
      const state = JSON.parse(configJson) as LayoutState
      applyLayoutState(state)
      saveLayoutState(state)
      return true
    } catch (error) {
      console.error('Failed to import layout:', error)
      return false
    }
  }

  // 监听状态变化并自动保存
  const setupAutoSave = () => {
    // 监听 store 中的关键状态变化
    watch(
      () => [
        uiStore.sidebarCollapsed,
        uiStore.sidebarVisible,
        uiStore.clientInfoVisible,
        uiStore.clientInfoExpanded,
        uiStore.activeTab,
        uiStore.theme,
        uiStore.density,
        uiStore.layoutMode,
        uiStore.panelStates
      ],
      () => {
        if (isInitialized.value) {
          const currentState = collectCurrentState()
          debouncedSave(currentState)
        }
      },
      { deep: true }
    )

    // 监听窗口大小变化
    watch(
      () => [uiStore.windowWidth, uiStore.windowHeight],
      () => {
        if (isInitialized.value) {
          const currentState = collectCurrentState()
          debouncedSave(currentState)
        }
      }
    )
  }

  // 处理页面可见性变化
  const handleVisibilityChange = () => {
    if (document.visibilityState === 'hidden') {
      // 页面隐藏时立即保存状态
      const currentState = collectCurrentState()
      saveLayoutState(currentState)
    }
  }

  // 处理页面卸载
  const handleBeforeUnload = () => {
    const currentState = collectCurrentState()
    saveLayoutState(currentState)
  }

  // 初始化
  const initialize = () => {
    // 加载保存的状态
    const savedState = loadLayoutState()
    
    if (savedState) {
      applyLayoutState(savedState)
    } else {
      // 使用默认状态
      const defaultState = getDefaultLayoutState()
      applyLayoutState(defaultState)
    }
    
    // 设置自动保存
    setupAutoSave()
    
    // 监听页面事件
    document.addEventListener('visibilitychange', handleVisibilityChange)
    window.addEventListener('beforeunload', handleBeforeUnload)
    
    isInitialized.value = true
  }

  // 清理
  const cleanup = () => {
    if (saveTimeout.value) {
      clearTimeout(saveTimeout.value)
    }
    
    document.removeEventListener('visibilitychange', handleVisibilityChange)
    window.removeEventListener('beforeunload', handleBeforeUnload)
    
    // 最后保存一次状态
    const currentState = collectCurrentState()
    saveLayoutState(currentState)
  }

  // 生命周期钩子
  onMounted(() => {
    initialize()
  })

  onUnmounted(() => {
    cleanup()
  })

  return {
    // 状态
    isInitialized,
    
    // 方法
    saveLayoutState,
    loadLayoutState,
    resetLayout,
    exportLayout,
    importLayout,
    collectCurrentState,
    applyLayoutState,
    
    // 生命周期
    initialize,
    cleanup
  }
}